<template>
  <div class="service-management">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryForm" class="search-form">
      <el-form-item label="用户名">
        <el-input
          v-model="queryForm.userName"
          placeholder="请输入用户名"
          clearable
        />
      </el-form-item>
      <el-form-item label="在线状态">
        <el-select
          v-model="queryForm.online"
          placeholder="请选择"
          clearable
          style="width: 100px"
        >
          <el-option label="在线" :value="true" />
          <el-option label="离线" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="值班状态">
        <el-select
          v-model="queryForm.onDuty"
          placeholder="请选择"
          clearable
          style="width: 100px"
        >
          <el-option label="值班中" :value="true" />
          <el-option label="未值班" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="queryForm.status"
          placeholder="请选择"
          clearable
          style="width: 100px"
        >
          <el-option label="正常" :value="0" />
          <el-option label="已禁用" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button
          v-if="userInfo?.userName === 'admin'"
          type="success"
          @click="handleAdd"
          >添加客服</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%" v-loading="loading" border>
      <el-table-column prop="userName" label="客服名称" />
      <el-table-column prop="avatar" label="头像">
        <template #default="scope">
          <el-avatar :src="baseUrl + scope.row.avatar" />
        </template>
      </el-table-column>
      <el-table-column prop="online" label="在线状态">
        <template #default="scope">
          <el-tag :type="scope.row.online ? 'success' : 'info'">
            {{ scope.row.online ? "在线" : "离线" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="onDuty" label="值班状态">
        <template #default="scope">
          <el-tag :type="scope.row.onDuty ? 'success' : 'warning'">
            {{ scope.row.onDuty ? "值班中" : "未值班" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'error'">
            {{ scope.row.status === 0 ? "正常" : "已禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间">
        <template #default="scope">
          {{ formatDate(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" link @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 添加客服弹窗 -->
  <el-dialog v-model="addDialogVisible" title="添加客服" width="500px">
    <el-form
      :model="addForm"
      :rules="addFormRules"
      ref="addFormRef"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="addForm.userName" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addForm.password" />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
          :action="uploadAvatar"
          :on-success="handleAvatarSuccess"
          :headers="uploadHeader"
        >
          <el-button type="primary">上传头像</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleAddConfirm">确定</el-button>
    </template>
  </el-dialog>
  <!-- 编辑客服弹窗 -->
  <el-dialog v-model="editDialogVisible" title="编辑客服" width="500px">
    <el-form
      :model="editForm"
      :rules="editFormRules"
      ref="editFormRef"
      label-width="85px"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="editForm.userName" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
          :action="uploadAvatar"
          :on-success="editAvatarUploadSuccess"
          :headers="uploadHeader"
          :show-file-list="false"
          :multiple="false"
        >
          <el-avatar :src="baseUrl + editForm.avatar" />
        </el-upload>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="editForm.password"
          placeholder="请输入密码,不修改密码不填写"
        />
      </el-form-item>
      <el-form-item label="账号状态" prop="status">
        <el-switch
          v-model="editForm.status"
          :active-value="0"
          :inactive-value="1"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleEditConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getServiceList,
  deleteService,
  addService,
  updateService,
} from "@/api";

const userInfo = ref(JSON.parse(localStorage.getItem("imUserInfo")));
// 添加客服弹窗
const baseUrl = import.meta.env.VITE_API_BASE_URL;
const uploadAvatar = baseUrl + "/v1/user/uploadAvatar";
const uploadHeader = {
  imtoken: `${localStorage.getItem("imtoken")}`,
};
const addDialogVisible = ref(false);
const addForm = ref({
  userName: "",
  password: "",
  avatar: "",
});
const handleAvatarSuccess = (res) => {
  addForm.value.avatar = res.data;
};
const addFormRules = ref({
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});
const addFormRef = ref(null);
const handleAddConfirm = () => {
  addFormRef.value.validate((valid) => {
    if (valid) {
      console.log("addForm", addForm.value);
      addService(addForm.value).then((res) => {
        ElMessage.success("添加成功");
        addDialogVisible.value = false;
        handleQuery();
        addForm.value = {
          userName: "",
          password: "",
        };
      });
    }
  });
};
const handleAdd = () => {
  addDialogVisible.value = true;
};

// 查询表单数据
const queryForm = ref({
  userName: "",
  online: null,
  onDuty: null,
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 查询方法
const handleQuery = async () => {
  loading.value = true;
  try {
    // 过滤掉值为null的字段
    const params = {};
    Object.entries(queryForm.value).forEach(([key, value]) => {
      if (value !== null && value !== "") {
        params[key] = value;
      }
    });
    const res = await getServiceList(params);
    tableData.value = res;
  } catch (error) {
    ElMessage.error("查询失败");
  } finally {
    loading.value = false;
  }
};

// 重置查询
const resetQuery = () => {
  queryForm.value = {
    userName: "",
    online: null,
    onDuty: null,
  };
  handleQuery();
};

// 编辑客服
const editDialogVisible = ref(false);
const editForm = ref({});
const editFormRules = ref({
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  status: [{ required: true, message: "请选择账号状态", trigger: "blur" }],
  avatar: [{ required: true, message: "请上传头像", trigger: "blur" }],
});
const editAvatarUploadSuccess = (res) => {
  editForm.value.avatar = res.data;
};
const editFormRef = ref(null);
const handleEdit = (row) => {
  // TODO: 实现编辑功能
  console.log("编辑", row);
  editDialogVisible.value = true;
  const data = JSON.parse(JSON.stringify(row));
  delete data.password;
  delete data.createTime;
  delete data.updateTime;
  delete data.userType;
  delete data.onDuty;
  delete data.online;
  delete data.userId;
  editForm.value = data;
};
const handleEditConfirm = () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      console.log("editForm", editForm.value);
      updateService(editForm.value).then((res) => {
        ElMessage.success("编辑成功");
        editDialogVisible.value = false;
        handleQuery();
      });
    }
  });
};

// 删除客服
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该客服吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteService(row._id);
      ElMessage.success("删除成功");
      handleQuery();
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString();
};

// 页面加载时查询数据
onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.service-management {
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #e6e6e6;
}
.avatar-tip {
  font-size: 12px;
  color: #999;
  display: block;
  margin-top: 10px;
}
</style> 